package com.ljh.utils;

import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @ProjectName:yeb
 * @Package:com.zlq.server.utils
 * @ClassName: FastDfsUtils
 * @description: FastDfs工具类
 * @author: Larry
 * @CreateDate:2021/5/8 9:33 下午
 */
public class FastDfsUtils {
    private static Logger LOGGER = LoggerFactory.getLogger(FastDfsUtils.class);

    /**
     * 初始化客户端
     * ClientGlobal.init(filePath)读取配置文件，并初始化属性
     */
    static {
        try {
            String filePath = new ClassPathResource("fastdfs_client.conf").getFile().getAbsolutePath();
            ClientGlobal.init(filePath);
        } catch (Exception e) {
            LOGGER.error("初始化FastDFS失败==========>", e.getMessage());
        }
    }

    /**
     * 生成tracker到服务器
     *
     * @return
     * @throws IOException
     */
    private static TrackerServer trackerServer() throws IOException {
        //return new TrackerClient().getTrackerServer();
        return new TrackerClient().getConnection();
    }

    /**
     * 生成storage客户端
     *
     * @return
     * @throws IOException
     */
    private static StorageClient getStorageClient() throws IOException {
        return new StorageClient(trackerServer(), null);
    }

    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    public static String[] upload(MultipartFile file) {
        String filename = file.getOriginalFilename();
        String[] uploadResults = null;
        LOGGER.info("文件名：" + filename);
        StorageClient storageClient = null;
        try {
            //获取storage客户端
            storageClient = getStorageClient();
            uploadResults = storageClient.upload_file(file.getBytes(),
                    filename.substring(filename.lastIndexOf(".") + 1), null);
        } catch (Exception e) {
            LOGGER.error("上传文件失败===========>", e.getMessage());
        }
        if (null == uploadResults) {
            LOGGER.error("上传失败", storageClient.getErrorCode());
        }
        return uploadResults;
    }


    /**
     * 获取文件信息
     *
     * @param groupName
     * @param remoteFileName
     * @return
     */
    public static FileInfo getFileInfo(String groupName, String remoteFileName) {
        StorageClient storageClient = null;
        try {
            storageClient = getStorageClient();
            return storageClient.get_file_info(groupName, remoteFileName);
        } catch (Exception e) {
            LOGGER.error("文件信息获取失败" + e.getMessage());
        }
        return null;
    }

    /**
     * 功能描述: <br>
     * 〈文件下载〉
     *
     * @param groupName
     * @param remoteFileName
     * @Author: Larry
     * @Date: 2021/5/8 10:04 下午
     * @return: java.io.InputStream
     */
    public static InputStream downFile(String groupName, String remoteFileName) {
        StorageClient storageClient = null;
        try {
            storageClient = getStorageClient();
            byte[] fileByte = storageClient.download_file(groupName, remoteFileName);
            InputStream inputStream = new ByteArrayInputStream(fileByte);
            return inputStream;
        } catch (Exception e) {
            LOGGER.error("文件下载失败" + e.getMessage());
        }
        return null;
    }

    /**
     * 删除文件
     *
     * @param groupName
     * @param remoteFileName
     */
    public static void deleteFile(String groupName, String remoteFileName) {
        StorageClient storageClient = null;
        try {
            storageClient = getStorageClient();
            storageClient.delete_file(groupName, remoteFileName);
        } catch (Exception e) {
            LOGGER.error("文件删除失败" + e.getMessage());
        }
    }

    /**
     * 获取文件完整路径
     *
     * @return
     */
    public static String getTrackerUrl() {
        TrackerClient trackerClient = null;
        TrackerServer trackerServer = null;
        StorageServer storeStorage = null;
        try {
            trackerClient = new TrackerClient();
            //trackerServer = trackerClient.getTrackerServer();
            trackerServer = trackerClient.getConnection();

            storeStorage = trackerClient.getStoreStorage(trackerServer);
        } catch (Exception e) {
            LOGGER.error("文件路径获取失败" + e.getMessage());
        }
        return "http://" + storeStorage.getInetSocketAddress().getHostString() + ":9888/";

    }
}
